<?php
/**
 * basic configurator
 *
 * @version:	0.1
 * @package:	global
 * @author:	alex_ez
 * @created:	12.02.2010 05:21
 *
 * @copyright:	(c) 2010 alex <qfox@ya.ru> yaroshevich aka alex_ez. All rights reserved.
 */


abstract class basic_configuratorAdminController extends adminController
{
	protected $form = '';
	protected $file = '';
	protected $data = '';
	protected $title = '';
	
	public function onstart( )
	{
		parent::onstart( );
		$this ->form = new form( $this );
	}
	
	public function showIndexPage( $p, $o )
	{
		$r = array( );
		
		//$form ->setOption( 'action', '/ajax/admin/users/edit/?id='.$user['id'] );
		$this ->form ->setData( $this ->data );
		
		// send form to template
		$r['fields'] = $this ->form ->getFieldSet( );
		$r['options'] = $this ->form ->getOptions( );
		$r['title'] = 'Configurate '.$this ->title;
		$r['template'] = 'admin/__form.tpl';
		
		return $r;
	}
	
	public function ajaxStore( $z )
	{
		// fetch post data & if data is bogus return error
		try { $p = $this ->form ->getPostData( ); } catch( FormException $e ) { return array( 'error' => $e ->getMessage( ) ); }
		
		if( file_put_contents( $this ->file, $this ->generate( $p ) ) === false )
			return array( 'error' => _('Config not stored.') );
		
		return array( 'error' => _('Config stored!') );
	}
	
	public function generate( $x )
	{
		$content = '';
		
		foreach( $x as $k => $vs )
		{
			if( !is_array( $vs ) )
			{
				$content .= sprintf( "%-15s \t= %s\n", $k, $this ->escape( $vs ) );
				continue;
			}
			
			$content .= sprintf( "\n[%s]\n", $k );
			foreach( $vs as $k => $v )
				$content .= sprintf( "%-15s \t= %s\n", $k, $this ->escape( $vs ) );
		}
		
		return $content;
	}
	
	protected function escape( $s )
	{
		return ctype_digit( $s ) ? (int)$s : sprintf( '"%s"', addslashes( $s ) );
	}
	
	protected $fieldSets;
	
	public function getFieldSet( $url = null, $decode = false )
	{
		$iurl = !is_null( $url ) ? $url : $this ->getInnerUrl( );
		$r = isset( $this ->fieldSets[ $iurl ] ) ? $this ->fieldSets[ $iurl ] : ''; //json::decode( $fields );
		
		return $decode ? json::decode( $r ) : $r;
	}

}


?>